import time
from datetime import datetime
from flask import (
    jsonify,
    Blueprint
)

from app import Log
from app.routes import Route
from app.routes.http_route import get_sid_by_openid
from app.routes.websocket_route import socketIo, namespace, add_one_message
from app.session import redis
from config.config import Base
from service import redis_service, mongo_service, third_service

name = 'android'
android_route = Blueprint(name, __name__, template_folder=Base.templateUrl)
logger = Log(name).init()
route = Route(name)
try_catch = route.android_wrapper


@android_route.route('/getMethods', methods=["GET"])
@try_catch
def get_methods(device_id, data):
    return jsonify({
        'err': 0,
        'msg': redis_service.session.get(Route.get_router_saver_key(name))
    })


#    <script src="http://api.map.baidu.com/api?v=2.0&ak=XHUkN6d9kzgsDdDym9ZIST7V3U5ezf5I"></script>#
@android_route.route('/location_upload', methods=["GET"])
@try_catch
def location_upload(device_id, json_data):
    """
    '{"time":1535310144699,"type":161,"lat":22.556803,"lon":113.935525,
    "addr":"\\u4e2d\\u56fd\\u5e7f\\u4e1c\\u7701\\u6df1\\u5733\\u5e02\\u5357\\u5c71\\u533a\\u827a\\u56ed\\u8def202",
    "radius":40,"networkType":"wf","gpsSwitch":0}'
     WayPoint::SN => $deviceId,
     WayPoint::UTCTIME => (new UTCDateTime(($now + 8 * 3600) * 1000)),
     WayPoint::INTTIME => $now,
     WayPoint::CLIENT_TIME => $clientTime,
     WayPoint::POINT => [intval($lon) / 1000000, intval($lat) / 1000000],
     WayPoint::TYPE => $type
    """

    # url = 'http://api.map.baidu.com/geoconv/v1/?coords=%s,%s&from=5&to=3&ak=XHUkN6d9kzgsDdDym9ZIST7V3U5ezf5I' % \
    #       (str(json_data['lon']), str(json_data['lat']))
    #
    # res = third_service.json_get(url)
    #
    # print(res)
    # if 'result' in res and len(res['result']) > 0:
    #     json_data['lat'] = res['result'][0]['y']
    #     json_data['lon'] = res['result'][0]['x']

    add_way_point(
        device_id, float(json_data['time']) / 1000, json_data['networkType'], json_data['lat'],
        json_data['lon'], json_data['addr'], json_data['radius'], json_data['gpsSwitch']
    )

    if 'user_id' in json_data and json_data['user_id']:
        sid = redis.hget(json_data['user_id'], 'sid')
        if sid:
            sid = sid.decode()
            socketIo.emit('location_upload', None, sid, namespace=namespace)

    return jsonify({
        'err': 0
    })


PARAM_ERROR = -33
AUTH_ERROR = -3
NO_DEVICE = -4
ACTION_ERROR = -5


@android_route.route('/bind', methods=["GET"])
@try_catch
def bind(device_id, data):
    device_id = data['deviceId']
    if not device_id:
        return jsonify({
            'err': PARAM_ERROR
        })

    device_info = mongo_service.find_one('devices', {
        "sn": device_id
    })
    if device_info:
        return jsonify({
            'err': 0,
            'msg': {
                'cmd': 'ack_bind'
                # 'appId': 'appId',
                # 'secretId': 'secretId',
                # 'secretKey': 'secretKey',
                # 'bucket': 'bucket',
                # 'endpoint': 'endpoint'
            }
        })
    else:
        return jsonify({
            'err': NO_DEVICE
        })


@android_route.route('/device_status_ack', methods=["GET"])
@try_catch
def device_status_ack(device_id, data):
    del data['mid']
    mongo_service.update('settings', {
        "sn": device_id
    }, {'$set': {
        "sn": device_id,
        'status': data
    }}, True)

    return jsonify({
        'err': 0
    })


@android_route.route('/upload_text_msg', methods=["GET"])
@try_catch
def upload_text_msg(device_id, data):
    #  data={"cmd":"upload_text_msg","role":"oYsiN0XPeZWoDb5oLoLH4T1B9pGM","content":"啊KKK"}
    add_one_message(device_id, data['role'], data['content'])
    msg_content = {"content": data['content'], "sender": device_id, "time": int(time.time()), "type": "0"}
    sid = get_sid_by_openid(data['role'])
    socketIo.emit('self_message', msg_content, sid, namespace=namespace)

    return jsonify({
        'err': 0
    })


@android_route.route('/upload_ps', methods=["GET"])
@try_catch
def upload_ps(device_id, data):
    #  data={"cmd":"upload_ps","role":"oYsiN0XPeZWoDb5oLoLH4T1B9pGM","url":"tao-1251758307.cos.ap-guangzhou.myqcloud.com/t1538057331506_shot_screen_temp.jpg"}
    url = "https://" + data['url']
    add_one_message(device_id, data['role'], url, 3)
    msg_content = {"content": url, "sender": device_id, "time": int(time.time()), "type": "3"}
    sid = get_sid_by_openid(data['role'])
    socketIo.emit('self_message', msg_content, sid, namespace=namespace)

    return jsonify({
        'err': 0
    })


@android_route.route('/device_screen_state', methods=["GET"])
@try_catch
def device_screen_state(device_id, data):
    data = {
        'status.device_screen_state': data['state']
    }
    mongo_service.update('settings', {
        "sn": device_id
    }, {'$set': data})

    return jsonify({
        'err': 0
    })


def add_way_point(sn, client_time, network_type, lat, lon, address, radius, gps_switch):
    if network_type == 'wf':
        network_type = 1

    data = {
        'sn': sn,
        'point': [
            lat, lon
        ],
        'address': address,
        'radius': radius,
        'network_type': network_type,
        'gps_switch': gps_switch,
        'client_time': client_time,
        'server_time': datetime.fromtimestamp(time.time() + 8 * 3600)
    }
    res = mongo_service.insert('way_point', data)


@android_route.route('/upload_voice_msg', methods=["GET"])
@try_catch
def upload_voice_msg(device_id, json_data):
    url = json_data['url']
    openid = json_data['role']
    timestamp = int(time.time())

    message_type = 2
    add_one_message(device_id, openid, url, message_type)

    user_info = mongo_service.find_one('users', {
        "openid": openid
    })

    devices = user_info.get('devices', {})
    nick_name = ''
    if device_id in devices:
        nick_name = devices[device_id]['name']

    room = get_sid_by_openid(openid)
    if room:
        socketIo.emit('self_message', {
            "content": url,
            "sender": device_id,
            "time": timestamp,
            "type": message_type
        }, room, namespace=namespace)

        redis_service.post_template_of_unread_message(openid, nick_name, timestamp, message_type)

        socketIo.emit('upload_voice_msg', url, room=room, namespace='/chat')

    return jsonify({
        'err': 0
    })
